package com.jh.user.service;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.jh.user.business.AppBrandBusiness;
import com.jh.user.business.ThirdLeveDistributionBusiness;
import com.jh.user.business.UserLoginRegisterBusiness;
import com.jh.user.pojo.AppImageText;
import com.jh.user.pojo.AppSlideshow;
import com.jh.user.pojo.ThirdLevelDistribution;
import com.jh.user.pojo.User;
import com.jh.user.util.AliOSSUtil;
import com.jh.user.util.Util;

import cn.jh.common.utils.CommonConstants;
import cn.jh.common.utils.ExceptionUtil;
import cn.jh.common.utils.TokenUtil;



@Controller
@EnableAutoConfiguration
public class AppSystemService {
		@Autowired
		Util util;

		private static final Logger LOG = LoggerFactory.getLogger(AppSystemService.class);
		
		@Value("${user.appsys.uploadpath}")
		private String realnamePic;
		
		@Value("${user.appsys.downloadpath}")
		private String downloadPath;
		
		@Value("${user.pay.url}")
		private String payUrl;
		
		@Autowired
		private UserLoginRegisterBusiness  userLoginRegisterBusiness;
		
		@Autowired
		private ThirdLeveDistributionBusiness  thirdLevelBusiness;
		
		@Autowired 
		private AppBrandBusiness appBrandBusiness;
		
		@Autowired 
		private AliOSSUtil aliOSSUtil;
		
		
		/**读取轮播图*/
		@RequestMapping(method=RequestMethod.POST,value="/v1.0/user/app/slideshow/query/brandid")
		public @ResponseBody Object downloadAppSlideshow(HttpServletRequest request,
				@RequestParam(value = "brand_id") long brandid
				){
			Map map = new HashMap();
			List<AppSlideshow> AppSlideshows=appBrandBusiness.findAppSlideshowByBrandId(brandid);
		   	map.put(CommonConstants.RESP_CODE,CommonConstants.SUCCESS);
		 	map.put(CommonConstants.RESULT, AppSlideshows);
			map.put(CommonConstants.RESP_MESSAGE, "成功");
			return map;
		}
		
		
		/**删除轮播图*/
		@RequestMapping(method=RequestMethod.POST,value="/v1.0/user/app/slideshow/delect/id")
		public @ResponseBody Object delAppSlideshow(HttpServletRequest request,
				@RequestParam(value = "id") long id
				){
			Map map = new HashMap();
			AppImageText appImageText = appBrandBusiness.findAppImageTextById(id);
			if (appImageText != null) {
				String ossObjectNamePrefix = AliOSSUtil.APP_SYS_SLIDESHOW + "-" + appImageText.getBrandId() + "-";
				String imgurl = appImageText.getImgurl();
				if (imgurl !=null && !"".equals(imgurl) && imgurl.contains(ossObjectNamePrefix)) {
					String objectName = imgurl.substring(imgurl.indexOf(ossObjectNamePrefix), imgurl.indexOf("?"));
					aliOSSUtil.deleteFileFromOss(objectName);
				}
			}
			appBrandBusiness.delAppSlideshowById(id);
		   	map.put(CommonConstants.RESP_CODE,CommonConstants.SUCCESS);
			map.put(CommonConstants.RESP_MESSAGE, "成功");
			return map;
		}
		
		/**轮播图
		 *   */
		@RequestMapping(method=RequestMethod.POST,value="/v1.0/user/app/slideshow/add/{token}")
		public @ResponseBody Object addAppSlideshow(HttpServletRequest request,
				@PathVariable("token") String token,
				@RequestParam(value = "url") String url,
				@RequestParam(value = "title") String title,
				@RequestParam(value = "id",  defaultValue = "0",  required=false) long id
				){
			Map map = new HashMap();
			long userId;
			try {
				userId = TokenUtil.getUserId(token);
			} catch (Exception e) {
		
				map.put(CommonConstants.RESP_CODE,CommonConstants.ERROR_TOKEN);
				map.put(CommonConstants.RESP_MESSAGE, "token无效");
				return map;
			
			}
			try {
				title=URLDecoder.decode(title, "UTF-8");
				url=URLDecoder.decode(url, "UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();LOG.error(ExceptionUtil.errInfo(e));
			}
			User user = userLoginRegisterBusiness.queryUserById(userId);
			String src ="slideshow/"+user.getBrandId();
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;  
		    MultipartFile file = multipartRequest.getFile("image");
		   if(file==null){
			   	map.put(CommonConstants.RESP_CODE,CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE, "请添加图片，图片不能为空");
				return map;
		   }
		   	/*File dir = new File(realnamePic+src); 
	    	//创建目录  
	        if (dir.mkdirs()) {  
	           
	        } else {  
	        	
	        } */
	        
			String ossObjectNamePrefix = AliOSSUtil.APP_SYS_SLIDESHOW + "-" + user.getBrandId() + "-";
	        
	    	String fileName = file.getOriginalFilename();
	    	String prefix=fileName.substring(fileName.lastIndexOf("."));
	    	fileName = System.currentTimeMillis()+prefix;
	    	
	    	String ossObjectName = ossObjectNamePrefix + fileName;
	    	try {
				aliOSSUtil.uploadStreamToOss(ossObjectName, file.getInputStream());
			} catch (IOException e1) {
				e1.printStackTrace();LOG.error(ExceptionUtil.errInfo(e1));
			}
	    	
	    	/*File  dest = new File(realnamePic+src+"/"+fileName);
	    	try {
				file.transferTo(dest);
			} catch (IllegalStateException e) {
				e.printStackTrace();LOG.error(ExceptionUtil.errInfo(e));
			} catch (IOException e) {
				e.printStackTrace();LOG.error(ExceptionUtil.errInfo(e));
			}*/
	    	
			String fileUrl = aliOSSUtil.getFileUrl(ossObjectName);
	    	
	    	AppSlideshow appSlideshow=appBrandBusiness.findAppSlideshowById(id);
		   	if(appSlideshow==null)
		   		appSlideshow=new AppSlideshow();
		   	appSlideshow.setBrandId(user.getBrandId());
		   	appSlideshow.setTitle(title);
		   	appSlideshow.setCreateTime(new Date());
			appSlideshow.setUrl(url);
//		   	appSlideshow.setImgurl(downloadPath+src+"/"+dest.getName());
		   	appSlideshow.setImgurl(fileUrl);
		   	appSlideshow.setCreateTime(new Date());
		   	appSlideshow.setUpdatetime(new Date());
		   	
		   	map.put(CommonConstants.RESP_CODE,CommonConstants.SUCCESS);
			map.put(CommonConstants.RESP_MESSAGE, "成功");
		  	map.put(CommonConstants.RESULT, appBrandBusiness.addAppSlideshow(appSlideshow));
			return map;
		}
		
		
		/***=======================================图文库================================
		 * @throws UnsupportedEncodingException ****/
				
		
		/**删除轮播图*/
		@RequestMapping(method=RequestMethod.POST,value="/v1.0/user/app/imagetext/delect/id")
		public @ResponseBody Object delAppText(HttpServletRequest request,
				@RequestParam(value = "id") long id
				){
			Map map = new HashMap();
			AppImageText appImageText = appBrandBusiness.findAppImageTextById(id);
			String ossObjectNamePrefix = AliOSSUtil.APP_SYS_SLIDESHOW + "-" + appImageText.getBrandId() + "-";
			List<String> listFiles = new ArrayList<String>();
			if(appImageText.getImgurl()!=null&&!appImageText.getImgurl().equals("")&&appImageText.getImgurl().contains(ossObjectNamePrefix)){
				String[] urls = appImageText.getImgurl().split(",");
				for (String string : urls) {
					String objectName = string.substring(string.indexOf(ossObjectNamePrefix), string.indexOf("?"));
					listFiles.add(objectName);
				}
				if (listFiles != null && listFiles.size()>0) {
					for(String fileName:listFiles){
						aliOSSUtil.deleteFileFromOss(fileName);
					}
				}
			}
			
			appBrandBusiness.delAppImageTextById(id);
		   	map.put(CommonConstants.RESP_CODE,CommonConstants.SUCCESS);
			map.put(CommonConstants.RESP_MESSAGE, "成功");
			return map;
		}
		/****
		 * 图文库=文
		 * 
		 * ***/		
		@RequestMapping(method=RequestMethod.POST,value="/v1.0/user/app/imagetext/add/txt/{token}")
		public @ResponseBody Object addAppText(HttpServletRequest request,
				@PathVariable("token") String token,
				@RequestParam(value = "content") String content,
				@RequestParam(value = "title") String title,
				@RequestParam(value = "remarks",  defaultValue = "",  required=false) String remarks,
				@RequestParam(value = "remarks1",  defaultValue = "",  required=false) String remarks1,
				@RequestParam(value = "id",  defaultValue = "0",  required=false) long id
				){
			Map map = new HashMap();
			long userId;
			try {
				userId = TokenUtil.getUserId(token);
			} catch (Exception e) {
		
				map.put(CommonConstants.RESP_CODE,CommonConstants.ERROR_TOKEN);
				map.put(CommonConstants.RESP_MESSAGE, "token无效");
				return map;
			
			}
			try {
				title=URLDecoder.decode(title, "UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();LOG.error(ExceptionUtil.errInfo(e));
			}
			User user = userLoginRegisterBusiness.queryUserById(userId);
	    	AppImageText appImageText=appBrandBusiness.findAppImageTextById(id);
		   	if(appImageText==null){
		   		appImageText=new AppImageText();
		   		appImageText.setRemarks(remarks);
			   	appImageText.setRemarks1(remarks1);
		   	}else{
		   		appImageText.setRemarks(remarks==null||remarks.equals("")?appImageText.getRemarks():remarks);
			   	appImageText.setRemarks1(remarks1==null||remarks1.equals("")?appImageText.getRemarks1():remarks1);
		   	}
		   		
		   	appImageText.setBrandId(user.getBrandId());
		   	appImageText.setTitle(title);
		   	appImageText.setContent(content);
		   	appImageText.setCreateTime(new Date());
		   	appImageText.setUpdatetime(new Date());
		   	
		   	map.put(CommonConstants.RESP_CODE,CommonConstants.SUCCESS);
			map.put(CommonConstants.RESP_MESSAGE, "成功");
		  	map.put(CommonConstants.RESULT, appBrandBusiness.addAppImageText(appImageText));
			return map;
		}
		
		/****
		 * 图文库=图
		 * 
		 * ***/	
		@RequestMapping(method=RequestMethod.POST,value="/v1.0/user/app/imagetext/add/image/{token}")
		public @ResponseBody Object addAppImage(HttpServletRequest request,
				@PathVariable("token") String token,
				@RequestParam(value = "id",  defaultValue = "0",  required=false) long id
				){
			Map map = new HashMap();
			long userId;
			try {
				userId = TokenUtil.getUserId(token);
			} catch (Exception e) {
		
				map.put(CommonConstants.RESP_CODE,CommonConstants.ERROR_TOKEN);
				map.put(CommonConstants.RESP_MESSAGE, "token无效");
				return map;
			
			}
			User user = userLoginRegisterBusiness.queryUserById(userId);
			String src ="imagetext/"+user.getBrandId();
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;  
			List<MultipartFile> files = multipartRequest.getFiles("image");
		   if(files==null||files.size()==0){
			   	map.put(CommonConstants.RESP_CODE,CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE, "请添加图片，图片不能为空");
				return map;
		   }
		   	/*File dir = new File(realnamePic+src); 
	    	//创建目录  
	        if (dir.mkdirs()) {  
	           
	        } else {  
	        }*/
	        
			String ossObjectNamePrefix = AliOSSUtil.APP_SYS_IMAGETEXT + "-" + user.getBrandId() + "-";
			String ossObjectName = "";

	        int i=1;
		   	String imgurls="";
		   	if(files!=null&&files.size()>0){
			   	for (MultipartFile file : files) {
			   		
			    	String fileName = file.getOriginalFilename();
			    	String prefix=fileName.substring(fileName.lastIndexOf("."));
			    	fileName = System.currentTimeMillis()+i+prefix;
			    	
					ossObjectName = ossObjectNamePrefix + fileName;
					
					try {
						aliOSSUtil.uploadStreamToOss(ossObjectName,file.getInputStream());
					} catch (IOException e1) {
						e1.printStackTrace();LOG.error(ExceptionUtil.errInfo(e1));
					}
					
					String fileUrl = aliOSSUtil.getFileUrl(ossObjectName);
					imgurls = imgurls + fileUrl + ",";
			    	
			    	i++;
			    	/*File  dest = new File(realnamePic+src+"/"+fileName);
//			    	imgurls+=downloadPath+src+"/"+dest.getName()+",";
			    	try {
						file.transferTo(dest);
					} catch (IllegalStateException e) {
						e.printStackTrace();LOG.error(ExceptionUtil.errInfo(e));
					} catch (IOException e) {
						e.printStackTrace();LOG.error(ExceptionUtil.errInfo(e));
					}*/
			   	}
		   	}
		 	AppImageText appImageText=null;
	        if(id==0){
	         	List<AppImageText> appImageTexts =appBrandBusiness.findAppImageTextByBrandId(user.getBrandId());
			   	if(appImageTexts!=null&&appImageTexts.size()>0){
			   		appImageText=appImageTexts.get(0);
			   	}
			   
	        }else{
	        	appImageText=appBrandBusiness.findAppImageTextById(id);
	        }
	    	if(appImageText==null ){
		   		map.put(CommonConstants.RESP_CODE,CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE, "失败");
			  	return map;
		   	}	
		   	appImageText.setImgurl(imgurls.substring(0, imgurls.length()-1));
		   	appImageText.setUpdatetime(new Date());
		   	
		   	map.put(CommonConstants.RESP_CODE,CommonConstants.SUCCESS);
			map.put(CommonConstants.RESP_MESSAGE, "成功");
		  	map.put(CommonConstants.RESULT, appBrandBusiness.addAppImageText(appImageText));
			return map;
		}
		
		/**读取图文库*/
		@RequestMapping(method=RequestMethod.POST,value="/v1.0/user/app/imagetext/query/brandid")
		public @ResponseBody Object downloadAppImageText(HttpServletRequest request,
				@RequestParam(value = "brand_id") long brandid
				){
			Map map = new HashMap();
			List<AppImageText> appImageTexts=appBrandBusiness.findAppImageTextByBrandId(brandid);
			List<Map>  filepaths=new ArrayList<Map>();
			for(AppImageText appImageText:appImageTexts){
				Map appImageText_ = new HashMap();
				appImageText_.put("id", appImageText.getId());
				appImageText_.put("title", appImageText.getTitle());
				appImageText_.put("content", appImageText.getContent());
				appImageText_.put("remarks", appImageText.getRemarks());
				appImageText_.put("remarks1", appImageText.getRemarks1());
				appImageText_.put("img_url",appImageText.getImgurl()!=null&&!appImageText.getImgurl().equals("")? appImageText.getImgurl().split(","):"");
				appImageText_.put("brand_id", appImageText.getBrandId());
				appImageText_.put("create_time", appImageText.getCreateTime());
				appImageText_.put("update_time", appImageText.getUpdatetime());
				filepaths.add(appImageText_);
			}
			
		   	map.put(CommonConstants.RESP_CODE,CommonConstants.SUCCESS);
		 	map.put(CommonConstants.RESULT, filepaths);
			map.put(CommonConstants.RESP_MESSAGE, "成功");
			return map;
		}
		/****===============================店铺管理=================================***/
		
		/**读取信息*/
		@RequestMapping(method=RequestMethod.POST,value="/v1.0/user/app/usersys/query/{token}")
		public @ResponseBody Object downloadAppUsersys(HttpServletRequest request,
				@PathVariable("token") String token
				){
			Map map = new HashMap();
			long userId;
			try {
				userId = TokenUtil.getUserId(token);
			} catch (Exception e) {
		
				map.put(CommonConstants.RESP_CODE,CommonConstants.ERROR_TOKEN);
				map.put(CommonConstants.RESP_MESSAGE, "token无效");
				return map;
			
			}
			User user = userLoginRegisterBusiness.queryUserById(userId);
			/***
			 * 1、获取当前用户所在贴牌的等级信息
			 * 2、获取用户的直推userIDs
			 * 3、获取用户的所有间推用户Ids
			 * 4、循环赋予各级别的直推间推个数
			 * 5、判断未实名未实名人数，已实名人数
			 * **/
			List<ThirdLevelDistribution> thirdLevelDistributions =thirdLevelBusiness.getAllThirdLevelPrd(user.getBrandId());
			Long[] preids={user.getId()};
			Long[] sonIds=userLoginRegisterBusiness.queryUserIdBypreUserIds(preids);
			String grandsonIds="";
			Long[] preuids=sonIds;
			if(sonIds!=null&&sonIds.length!=0&&sonIds[0]>0){
				for(int i=0 ;true;i++){
					Long[] pids=userLoginRegisterBusiness.queryUserIdBypreUserIds(preuids);
					if(pids!=null&&pids.length>0&&pids[0]>0){
						preuids=new Long[pids.length];
						preuids=pids;
						for(Long uid:pids){
							grandsonIds+=uid+",";
						}
					}else{
						break;
					}
				}
			}
			
			if(grandsonIds.length()>0){
				grandsonIds = grandsonIds.substring(0, grandsonIds.length()-1);
				String[] str1 = grandsonIds.split(",");
		        preuids = new Long[str1.length];
		        for (int j = 0; j < str1.length; j++) {
		        	preuids[j] = Long.valueOf(str1[j]);
		        }
			}else{
				 preuids=null;
			}
			/****
			 *管理等级
			 * ***/
			List<Map> gradeList = new ArrayList<Map>();
			if(thirdLevelDistributions!=null)
			for(ThirdLevelDistribution thirdLevelDistribution :thirdLevelDistributions){
				Map<String,Object> grade =new HashMap();
				grade.put("grade", thirdLevelDistribution.getGrade());
				grade.put("name", thirdLevelDistribution.getName());
				grade.put("TrueFalseBuy", thirdLevelDistribution.getTrueFalseBuy());
				grade.put("url", "");
				if(sonIds!=null&&sonIds.length>0&&sonIds[0]>0){
					Long[] GradesonIds = userLoginRegisterBusiness.queryUserIdBypreUserIdsAndGrade(thirdLevelDistribution.getGrade()+"", sonIds);
					if(GradesonIds!=null&&GradesonIds.length>0&&GradesonIds[0]>0){
						grade.put("GradesonIds", GradesonIds.length);
					}else{
						grade.put("GradesonIds", 0);
					}
					
				}else{
					grade.put("GradesonIds", 0);
				}
				if(preuids!=null&&preuids.length>0&&preuids[0]>0){
					Long[] Gradepreuids=userLoginRegisterBusiness.queryUserIdBypreUserIdsAndGrade(thirdLevelDistribution.getGrade()+"", preuids) ;
					if(Gradepreuids!=null&&Gradepreuids.length>0&&Gradepreuids[0]>0){
						grade.put("Gradepreuids", Gradepreuids.length);
					}else{
						grade.put("Gradepreuids", 0);
					}
					
				}else{
					grade.put("Gradepreuids", 0);
				}
				gradeList.add(grade);
			}
			{
				Map grade =new HashMap();
				grade.put("grade", 0);
				grade.put("name", "普通用户");
				grade.put("url", "");
				if(sonIds!=null&sonIds.length>0&&sonIds[0]>0){
					Long[] GradesonIds = userLoginRegisterBusiness.queryUserIdBypreUserIdsAndGrade(0+"", sonIds);
					if(GradesonIds!=null&&GradesonIds.length>0&&GradesonIds[0]>0){
						grade.put("GradesonIds", GradesonIds.length);
					}else{
						grade.put("GradesonIds", 0);
					}
					
				}else{
					grade.put("GradesonIds", 0);
				}
				if(preuids!=null&&preuids.length>0&&preuids[0]>0){
					Long[] Gradepreuids=userLoginRegisterBusiness.queryUserIdBypreUserIdsAndGrade(0+"", preuids) ;
					if(Gradepreuids!=null&&Gradepreuids.length>0&&Gradepreuids[0]>0){
						grade.put("Gradepreuids", Gradepreuids.length);
					}else{
						grade.put("Gradepreuids", 0);
					}
					
				}else{
					grade.put("Gradepreuids", 0);
				}
				
				gradeList.add(grade);
			}
			String talluid="";
			if(sonIds!=null){
				for(Long uid:sonIds){
					talluid+=uid+",";
				}
			}
			if(preuids!=null){
				for(Long uid:preuids){
					talluid+=uid+",";
				}
			}
			Long[] talluidl={};
			if(talluid.length()>0){
				talluid = talluid.substring(0, talluid.length()-1);
				String[] str1 = talluid.split(",");
				talluidl = new Long[str1.length];
		        for (int j = 0; j < str1.length; j++) {
		        	talluidl[j] = Long.valueOf(str1[j]);
		        }
			}
			Map truefalse =new HashMap();
			Long[] truenum=null;
			if(talluidl!=null&&talluidl.length>0&&talluidl[0]>0){
				truenum=userLoginRegisterBusiness.queryUserIdBypreUserIdsAndrealnameStatus("1", talluidl);
			}
			
			
			truefalse.put("truenum",truenum==null?0:truenum.length );
			truefalse.put("falsenum",truenum==null?talluidl.length:talluidl.length-truenum.length );
			truefalse.put("thirdLevelDistribution", gradeList);
		   	map.put(CommonConstants.RESP_CODE,CommonConstants.SUCCESS);
		 	map.put(CommonConstants.RESULT,truefalse);
			map.put(CommonConstants.RESP_MESSAGE, "成功");
			return map;
		}
		
		
		
}
